package com.hydra.auth.utils;

import com.hydra.auth.entity.IdGenerator;
import com.hydra.auth.service.IdGeneratorService;
import com.hydra.base.common.Constant;
import com.hydra.base.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class IdUtil {

	public static IdGeneratorService idGeneratorRepository;
	public static RedissonClient redissonClient;

	/**缓存保存过的数据*/
	private static final Map<String, Long> cacheMap = new HashMap<>();

	public static void init(){
		if(idGeneratorRepository == null){
			idGeneratorRepository = SpringUtils.getBean(IdGeneratorService.class);
		}
		if(redissonClient == null){
			redissonClient = SpringUtils.getBean(RedissonClient.class);
		}
	}

	/**生成id*/
	public static long nextId(String name){
		init();
		RLock lock = redissonClient.getLock(Constant.REDISSON_LOCK_ID_GENERATOR);
		lock.lock(1, TimeUnit.MINUTES);//锁一分钟也够了
		long id = 0;
		try {
			IdGenerator target = idGeneratorRepository.findByName(name);
			if(target == null){
				target = new IdGenerator();
				target.initEntity();
				target.setName(name);
				target.setValue(0L);
			}
			id = target.getValue() + 1;
			target.setValue(id);
			idGeneratorRepository.saveOrUpdate(target);
		} catch (Exception e) {
			log.error("生成id异常", e);
		}   finally {
			lock.unlock();
		}
		return id;
	}

}
